package com.drivemanage.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.drivemanage.dao.CarInfoDao;
import com.drivemanage.entry.CarInfo;
import com.drivemanage.entry.DriveResult;
import com.drivemanage.utils.OpenUtils;

@Service
@Transactional
public class CarInfoServiceImpl implements CarInfoService {

    Logger log = Logger.getLogger("CarInfoServiceImpl");

    @Resource
    private CarInfoDao carInfoDao;

    @Override
    public DriveResult uploadImg(MultipartFile carpic, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        byte[] logoBytes = null;
        if (!carpic.isEmpty()) {
            try {
                logoBytes = carpic.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File("sofapic")));
                stream.write(logoBytes);
                stream.close();
            }
            catch (Exception e) {
                return new DriveResult(DriveResult.ERROR_CODE, "上传图片出错!请重新上传", "");
            }
        }
        else {
            return new DriveResult(DriveResult.ERROR_CODE, "上传的图片有误!请重新选择", "");
        }
        if (OpenUtils.isEmpty(logoBytes) || logoBytes.length > 15 * 1024 * 1024) {
            return new DriveResult(DriveResult.ERROR_CODE, "上传图片过大!请重新选择", "");
        }
        String carId = OpenUtils.createCarID();
        CarInfo carInfo = new CarInfo(carId, 0, logoBytes, "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "",
                "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
        carInfo.setIs_valid("0");// 设置为失效
        carInfoDao.addCarEmg(carInfo);
        return new DriveResult(DriveResult.SUCCESS_CODE, "图片上传成功", carId);
    }

    @Override
    public DriveResult addCarsInfo(String carid, double carprice, String pinpai, String chexing, String chexingname,
            String jibie, String fadongji, String biansuxiang, String cheshen, String ckg, String zhouju,
            String youxiang, String zuoweishu, double pailiang, String jinqi, String qigang, String maxmali,
            String maxnj, String ranyoutype, String ranhoubianhao, String gongyou, String paifang, String qudong,
            String zhuli, String qianxuangua, String houxuangua, String qianzhidong, String houzhidong,
            String zhuchezhidong, String yuanguangdeng, String jinguangdeng) {
        CarInfo carInfo = new CarInfo(carid, carprice, "", pinpai, chexing, chexingname, jibie, fadongji, biansuxiang,
                cheshen, ckg, zhouju, youxiang, zuoweishu, pailiang, jinqi, qigang, maxmali, maxnj, ranyoutype,
                ranhoubianhao, gongyou, paifang, qudong, zhuli, qianxuangua, houxuangua, qianzhidong, houzhidong,
                zhuchezhidong, yuanguangdeng, jinguangdeng, "", "");
        carInfo.setIs_valid("1");// 设置为生效
        carInfoDao.insertCarInfo(carInfo);
        return new DriveResult(DriveResult.SUCCESS_CODE, "信息添加成功", "");
    }

	@Override
	public DriveResult getCarInfo() {
		List<CarInfo> carInfos=new ArrayList<CarInfo>();
		carInfos=carInfoDao.getCarInfos();
		//对返回值进行处理
		if(OpenUtils.isEmpty(carInfos)){
			return new DriveResult(DriveResult.ERROR_CODE, "未查询到车辆信息", "");
		}
		for (CarInfo car : carInfos) {
            byte[] sofapic = (byte[]) car.getCarimg();
            String picPath = OpenUtils.PIC_PATH + "img" + car.getCarid() + ".jpg";
            File picFile = new File(picPath);
            if (!picFile.exists()) {

                try {
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(picPath)));
                    stream.write(sofapic);
                    stream.close();
                }
                catch (Exception e) {
                    e.printStackTrace();
                    return new DriveResult(DriveResult.ERROR_CODE, "图片加载失败!", "");
                }
            }
            car.setCarimg(picPath.substring(picPath.indexOf("carPics")));
        }
		return new DriveResult(DriveResult.SUCCESS_CODE, "查询成功", carInfos);
	}

	@Override
	public DriveResult getCarInfoOrderBy(String name, String type,
			String price, String t, String ordertype) {
		@SuppressWarnings("rawtypes")
		OpenUtils openutils=new OpenUtils();
		Map param=openutils.changeParam(name, type, price, t, ordertype);
		System.out.println("请求参数"+param);
		List<CarInfo> carInfos=carInfoDao.getCarInfoOrder(param);
		//对返回值进行处理
				if(OpenUtils.isEmpty(carInfos)){
					return new DriveResult(DriveResult.ERROR_CODE, "未查询到车辆信息", "");
				}
				for (CarInfo car : carInfos) {
		            byte[] sofapic = (byte[]) car.getCarimg();
		            String picPath = OpenUtils.PIC_PATH + "img" + car.getCarid() + ".jpg";
		            File picFile = new File(picPath);
		            if (!picFile.exists()) {

		                try {
		                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(picPath)));
		                    stream.write(sofapic);
		                    stream.close();
		                }
		                catch (Exception e) {
		                    e.printStackTrace();
		                    return new DriveResult(DriveResult.ERROR_CODE, "图片加载失败!", "");
		                }
		            }
		            car.setCarimg(picPath.substring(picPath.indexOf("carPics")));
		        }
				return new DriveResult(DriveResult.SUCCESS_CODE, "查询成功", carInfos);
	}


	@Override
	public DriveResult getCarInfoByCarId(String carid) {
		List<CarInfo> carInfos=carInfoDao.getCarInfoByCarId(carid);
		if(OpenUtils.isEmpty(carInfos)){
			return new DriveResult(DriveResult.ERROR_CODE, "未查询到车辆信息", "");
		}
		for (CarInfo car : carInfos) {
            byte[] sofapic = (byte[]) car.getCarimg();
            String picPath = OpenUtils.PIC_PATH + "img" + car.getCarid() + ".jpg";
            File picFile = new File(picPath);
            if (!picFile.exists()) {

                try {
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(picPath)));
                    stream.write(sofapic);
                    stream.close();
                }
                catch (Exception e) {
                    e.printStackTrace();
                    return new DriveResult(DriveResult.ERROR_CODE, "图片加载失败!", "");
                }
            }
            car.setCarimg(picPath.substring(picPath.indexOf("carPics")));
        }
		return new DriveResult(DriveResult.SUCCESS_CODE, "查询成功", carInfos);
	}
}
